package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"mwwow_service_go/model"
	"time"
)

func CheckLogin(c *gin.Context) {
	var user model.User
	err := json.NewDecoder(c.Request.Body).Decode(&user)
	if err != nil {
		log.Fatalln(err)
	}
	data, isSuccess, err := user.CheckLogin()
	if err != nil || isSuccess != true {
		c.JSON(200, gin.H{
			"code":  1,
			"error": "登陆失败",
		})
		return
	}
	openId := time.Now().UnixNano()
	c.JSON(200, gin.H{
		"code":   0,
		"msg":    "登陆成功",
		"openId": openId,
		"data":   data,
	})
}

func GetUser(c *gin.Context) {
	var user model.User
	data, err := user.GetUser()
	if err != nil {
		c.JSON(500, gin.H{
			"code": 1,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": data,
	})
}

func GetUserById(c *gin.Context) {
	var user model.User
	id := c.Param("id")
	data, err := user.GetUserById(id)
	if err != nil {
		c.JSON(500, gin.H{
			"code": 1,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": data,
	})
}

func ChangePassword(c *gin.Context) {
	var password model.Password
	id := c.Param("id")
	err := json.NewDecoder(c.Request.Body).Decode(&password)
	if err != nil {
		log.Fatalln(err)
		return
	}
	isSuccess, err := password.ChangePassword(id)
	if err != nil || isSuccess != true {
		c.JSON(200, gin.H{
			"code":  1,
			"error": err,
		})
	}
	c.JSON(200, gin.H{
		"code": 0,
	})
}
